<template>
    <el-dialog v-model="dialogFormVisible" title="菜单授权">
        <el-tree :data="treeData" :props="props" show-checkbox node-key="menuId" :check-strictly="true"
            :default-expanded-keys="defaultExpandedKey" :default-checked-keys="defaultCheckedKey"
            :expand-on-click-node="false" ref="menuTree" v-loading="isLoading">
            <template #default="{ node, data }">
                <span class="custom-tree-node">
                    <el-icon class="menuIcon">
                        <component :is="data.icon" />
                    </el-icon>
                    <span>{{ node.label }}</span>
                </span>
            </template>
        </el-tree>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">返回</el-button>
                <el-button :disabled="isLoading" type="primary" @click="author">确认</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup name="authorMenu">
import { ref } from 'vue'
import api from "@/api"
import { ElMessage } from 'element-plus'

const isLoading = ref(false)
const dialogFormVisible = ref(false)
const role = ref('')
const defaultExpandedKey = ref([])
const defaultCheckedKey = ref([])
const treeData = ref()
const menuTree = ref()
const props = {
    children: 'children',
    label: 'title'
}
const init = (roleId) => {
    isLoading.value = true
    defaultExpandedKey.value = []
    defaultCheckedKey.value = []
    dialogFormVisible.value = true
    role.value = roleId
    api.get('/author/menu/menuList').then(res => {
        if (res.data.code === 200) {
            treeData.value = res.data.data;
            api.post('/author/menu/authorMenuList', { roleId: roleId }).then(authorRes => {
                if (authorRes.data.code === 200) {
                    defaultExpandedKey.value = authorRes.data.data.defaultExpandedKey
                    defaultCheckedKey.value = authorRes.data.data.defaultCheckedKey
                    isLoading.value = false
                } else {
                    ElMessage.error(authorRes.data.msg)
                }
            })
        } else {
            ElMessage.error(res.data.msg)
        }
    })
}

const author = async () => {
    isLoading.value = true
    const allCheckMenus = menuTree.value.getCheckedNodes();
    const menuIds = allCheckMenus.map(item => item.menuId)
    const params = new Map()
    params.set(role.value, menuIds)
    const res = await api.post('/author/role/authorMenu', Object.fromEntries(params))
    if (res.data.code === 200) {
        dialogFormVisible.value = false
        ElMessage.success(res.data.msg)
    } else {
        ElMessage.error(res.data.msg)
    }
    isLoading.value = false
}
defineExpose({
    init
});
</script>
<style scoped lang="less"></style>